package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Slf4j
public class RequestUtils {

    /**
     * 打印请求头信息
     *
     * @param request
     */
    public static void printHeaders(HttpServletRequest request) {
        log.info("============= 请求头开始 ============");
        Enumeration<String> iterator = request.getHeaderNames();
        while (iterator.hasMoreElements()) {
            String key = iterator.nextElement();
            log.info("{}:{}", key, request.getHeader(key));
        }
        log.info("============= 请求头结束 ============");
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
}
